package com.alibaba.dubbo.common.utils;

import com.alibaba.dubbo.common.logger.Logger;

/**
 * Created by sunlei on 2016/2/2.
 */
public class DebugHelper {
    private static String lineSeparator = System.getProperty("line.separator", "\n");

    public static void printStack(Logger logger) {
        StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();

        StringBuilder sb=new StringBuilder();
        for (StackTraceElement stackTraceElement : stackTraceElements) {
            sb.append(stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName() + ":" + stackTraceElement.getLineNumber());
            sb.append(lineSeparator);
        }
        logger.info(sb.toString());
    }

    public static void printAllThreads(Logger logger) {
        Thread[] threads = findAllThreads();

        if (threads.length > 0) {
            StringBuilder sb=new StringBuilder();
            for (Thread thread : threads) {
                sb.append(thread.getName() + ":" + thread.getId());
                sb.append(lineSeparator);
            }

            logger.info(sb.toString());
        }
    }

    public static Thread[] findAllThreads() {
        ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
        ThreadGroup topGroup = threadGroup;
        //遍历线程组树，获取根线程组
        while (threadGroup != null) {
            topGroup = threadGroup;
            threadGroup = threadGroup.getParent();
        }

        //激活的线程数加倍
        int estimatedSize = topGroup.activeCount() * 2;
        Thread[] stackList = new Thread[estimatedSize];
        //获取根线程组的所有线程
        int actualSize = topGroup.enumerate(stackList);
        Thread[] list = new Thread[actualSize];
        System.arraycopy(stackList, 0, list, 0, actualSize);
        return list;
    }

}

